<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人OJ系统</title>
    <style>
        /* 基础样式保留，去除可能干扰的动画 */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        html, body { width: 100%; height: 100%; font-family: Arial, sans-serif; }
        
        .navbar {
            width: 100%;
            height: 50px;
            background-color: black;
            overflow: hidden;
        }
        .navbar a {
            display: inline-block;
            width: 80px;
            color: white;
            font-size: large;
            line-height: 50px;
            text-decoration: none;
            text-align: center;
            cursor: pointer;
        }
        .navbar a:hover { background-color: green; }
        .user-area { float: right; }
        .user-area a { margin-left: 10px; }
        #loginArea .username {
            color: white;
            line-height: 50px;
            margin-right: 10px;
            display: inline-block;
        }
        
        .content {
            width: 800px;
            margin: 0 auto;
            text-align: center;
            margin-top: 200px;
        }
        .font_ {
            display: block;
            margin-top: 20px;
            text-decoration: none;
            color: #000;
            font-size: larger;
        }
        
        .modal-mask {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            width: 300px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 8px 15px;
            margin-right: 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button[type="submit"] {
            background-color: #4CAF50;
            color: white;
        }
        button[type="button"] {
            background-color: #f44336;
            color: white;
        }
        .alert {
            position: fixed;
            top: 20px; left: 50%;
            transform: translateX(-50%);
            padding: 10px 20px;
            border-radius: 4px;
            color: white;
            display: none;
            z-index: 1001;
        }
        .error-alert { background-color: #f44336; }
        .success-alert { background-color: #28a745; }
        .loading {
            display: none;
            text-align: center;
            margin-top: 15px;
        }
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .error-message {
            color: #f44336;
            font-size: 0.9em;
            margin-top: 5px;
            display: none;
        }
    </style>
</head>
<body>
    <!-- 提示框 -->
    <div id="registerSuccessAlert" class="alert success-alert">注册成功，用户可以登录进行答题啦！</div>
    <div id="loginSuccessAlert" class="alert success-alert">登录成功，可以开始答题了！</div>
    <div id="userExistsAlert" class="alert error-alert">用户名已存在</div>
    <div id="loginFailedAlert" class="alert error-alert">用户名或密码错误</div>
    <div id="registerErrorAlert" class="alert error-alert">注册失败，请重试</div>
    <div id="networkErrorAlert" class="alert error-alert">网络错误，请检查接口是否可达</div>
    <!-- 新增未登录提示框 -->
    <div id="notLoginAlert" class="alert error-alert">请先注册/登录账号</div>

    <!-- 注册弹窗 -->
    <div class="modal-mask" id="registerModal">
        <div class="modal-content">
            <h2>注册账号</h2>
            <form id="registerForm">
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" name="username" required minlength="3" maxlength="20">
                    <div class="error-message" id="regUsernameError">用户名长度必须在3-20个字符之间</div>
                </div>
                <div class="form-group">
                    <label>密码</label>
                    <input type="password" name="password" required minlength="6">
                    <div class="error-message" id="regPasswordError">密码长度不能少于6个字符</div>
                </div>
                <button type="submit">注册</button>
                <button type="button" onclick="closeRegisterModal()">取消</button>
                <div class="loading" id="regLoading">
                    <div class="spinner"></div>
                    <span>处理中...</span>
                </div>
            </form>
        </div>
    </div>

    <!-- 登录弹窗 -->
    <div class="modal-mask" id="loginModal">
        <div class="modal-content">
            <h2>用户登录</h2>
            <form id="loginForm">
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" name="username" required>
                </div>
                <div class="form-group">
                    <label>密码</label>
                    <input type="password" name="password" required>
                </div>
                <button type="submit">登录</button>
                <button type="button" onclick="closeLoginModal()">取消</button>
                <div class="loading" id="loginLoading">
                    <div class="spinner"></div>
                    <span>处理中...</span>
                </div>
            </form>
        </div>
    </div>

    <div class="container">
        <div class="navbar">
            <a href="#">首页</a>
            <a id="problemsLink">题库</a>
            <a href="#">竞赛</a>
            <a href="#">讨论</a>
            <a href="#">求职</a>
            
            <div class="user-area" id="notLoginArea">
                <a href="javascript:;" id="loginBtn">登录</a>
                <a href="javascript:;" id="registerBtn">注册</a>
            </div>
            
            <div class="user-area" id="loginArea" style="display: none;">
                <span class="username" id="usernameDisplay"></span>
                <a href="javascript:;" id="logoutBtn">退出</a>
            </div>
        </div>
        
        <div class="content">
            <h1 class="font_">欢迎来到我的OnlineJudge平台</h1>
            <p class="font_">个人独立开发的在线OJ系统</p>
            <a class="font_" id="startProgrammingLink">点击我开始编程啦!</a>
        </div>
    </div>

    <script>
        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
        };

        // 检查登录状态（简化版）
        function checkLoginStatus() {
            fetch('/api/check_login')
                .then(res => res.text())
                .then(username => {
                    const notLoginArea = document.getElementById('notLoginArea');
                    const loginArea = document.getElementById('loginArea');
                    const usernameDisplay = document.getElementById('usernameDisplay');
                    
                    if (username !== 'not_login' && username.trim() !== '') { 
                        // 登录状态：显示昵称 + 退出，隐藏登录/注册
                        notLoginArea.style.display = 'none';
                        loginArea.style.display = 'block';
                        usernameDisplay.textContent = username; // 渲染昵称
                    } else {
                        // 未登录状态：显示登录/注册，隐藏昵称 + 退出
                        notLoginArea.style.display = 'block';
                        loginArea.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('检查登录状态出错:', error);
                });
        }

        // 注册弹窗控制
        document.getElementById('registerBtn').addEventListener('click', () => {
            document.getElementById('registerModal').style.display = 'flex';
        });

        function closeRegisterModal() {
            document.getElementById('registerModal').style.display = 'none';
            document.getElementById('registerForm').reset();
            document.getElementById('regLoading').style.display = 'none';
            document.getElementById('regUsernameError').style.display = 'none';
            document.getElementById('regPasswordError').style.display = 'none';
            hideAllAlerts();
        }

        // 登录弹窗控制
        document.getElementById('loginBtn').addEventListener('click', () => {
            document.getElementById('loginModal').style.display = 'flex';
        });

        function closeLoginModal() {
            document.getElementById('loginModal').style.display = 'none';
            document.getElementById('loginForm').reset();
            document.getElementById('loginLoading').style.display = 'none';
            hideAllAlerts();
        }

        // 隐藏所有提示框
        function hideAllAlerts() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => alert.style.display = 'none');
        }

        // 注册表单提交
        document.getElementById('registerForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const username = this.username.value.trim();
            const password = this.password.value;
            
            // 客户端验证
            let isValid = true;
            if (username.length < 3 || username.length > 20) {
                document.getElementById('regUsernameError').style.display = 'block';
                isValid = false;
            } else {
                document.getElementById('regUsernameError').style.display = 'none';
            }
            if (password.length < 6) {
                document.getElementById('regPasswordError').style.display = 'block';
                isValid = false;
            } else {
                document.getElementById('regPasswordError').style.display = 'none';
            }
            if (!isValid) return;

            // 显示加载状态
            document.getElementById('regLoading').style.display = 'block';

            const params = new URLSearchParams();
            params.append('username', username);
            params.append('password', password);

            fetch('/api/register', {
                method: 'POST',
                body: params
            })
            .then(res => {
                if (!res.ok) {
                    throw new Error(`HTTP状态码错误: ${res.status}`);
                }
                return res.text();
            })
            .then(msg => {
                document.getElementById('regLoading').style.display = 'none';
                console.log('注册接口返回:', msg);
                
                if (msg === 'success') {
                    closeRegisterModal();
                    document.getElementById('registerSuccessAlert').style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('registerSuccessAlert').style.display = 'none';
                        document.getElementById('loginModal').style.display = 'flex';
                    }, 2000);
                } else if (msg === 'user_exists') {
                    document.getElementById('userExistsAlert').style.display = 'block';
                    setTimeout(hideAllAlerts, 2000);
                } else {
                    document.getElementById('registerErrorAlert').style.display = 'block';
                    setTimeout(hideAllAlerts, 2000);
                }
            })
            .catch(error => {
                document.getElementById('regLoading').style.display = 'none';
                console.error('注册网络错误详情:', error);
                document.getElementById('networkErrorAlert').style.display = 'block';
                setTimeout(hideAllAlerts, 2000);
            });
        });

        // 登录表单提交
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const username = this.username.value.trim();
            const password = this.password.value;
            
            document.getElementById('loginLoading').style.display = 'block';

            const params = new URLSearchParams();
            params.append('username', username);
            params.append('password', password);

            fetch('/api/login', {
                method: 'POST',
                body: params
            })
            .then(res => {
                if (!res.ok) throw new Error(`HTTP状态码错误: ${res.status}`);
                return res.text();
            })
            .then(msg => {
                document.getElementById('loginLoading').style.display = 'none';
                console.log('登录接口返回:', msg);
                
                if (msg === 'success') {
                    closeLoginModal();
                    document.getElementById('loginSuccessAlert').style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('loginSuccessAlert').style.display = 'none';
                        checkLoginStatus();
                    }, 2000);
                } else {
                    document.getElementById('loginFailedAlert').style.display = 'block';
                    setTimeout(hideAllAlerts, 2000);
                }
            })
            .catch(error => {
                document.getElementById('loginLoading').style.display = 'none';
                console.error('登录网络错误详情:', error);
                document.getElementById('networkErrorAlert').style.display = 'block';
                setTimeout(hideAllAlerts, 2000);
            });
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            fetch('/api/logout')
                .then(() => checkLoginStatus())
                .catch(error => {
                    console.error('退出登录错误:', error);
                    document.getElementById('networkErrorAlert').style.display = 'block';
                    setTimeout(hideAllAlerts, 2000);
                });
        });

        // 题库跳转控制（核心修改：未登录时显示正确提示）
        document.getElementById('problemsLink').addEventListener('click', () => {
            checkLoginAndRedirect('/all_questions');
        });
        document.getElementById('startProgrammingLink').addEventListener('click', () => {
            checkLoginAndRedirect('/all_questions');
        });

        function checkLoginAndRedirect(url) {
            fetch('/api/check_login')
                .then(res => res.text())
                .then(username => {
                    if (username !== 'not_login' && username) {
                        window.location.href = url;
                    } else {
                        // 关键修改：显示“请先注册/登录账号”提示，而非登录失败提示
                        document.getElementById('notLoginAlert').style.display = 'block';
                        setTimeout(hideAllAlerts, 2000);
                    }
                });
        }
    </script>
</body>
</html>
    
    
    


